<!-- 功能管理页面 -->
<script setup lang='ts'>
import {ref, computed, PropType, watch, onBeforeMount} from 'vue'
import  dDialog  from '@/components/dDialog/dDialog.vue'
import {FormRules, ElMessage} from 'element-plus'
import {FromItem} from '@/components/dFrom/dFrom'
import dFrom from '@/components/dFrom/dFrom.vue'
import { instrumentSave, SaveData, getAllData} from '@/api/instrument/Inspection'
import { Normal, PassWord, Number, Collect, NoChineseEmty, NotLeadingAndTrailingSpaces} from '@/util/common'
import timeLine from '@/components/timeLine.vue'
import {PositiveInteger, transfDicArrData} from '@/util/common'
import {SeleteData} from '@/api/config'
import userCommon from '@/store/common'
const common = userCommon.setup().store
const emits = defineEmits(['cancel', 'confirm', 'close'])
const props = defineProps({
  //显示
  showDialog:{
    type:Boolean,
    required:true
  },
  popData:{
    type:Object as PropType<SaveData>,
    required:true
  },
  disabled:{
    type:Boolean,
    default:true
  }
})
const formData = computed(() => {
  return props.popData
})
const fromDatas = ref<SaveData>({communicationType:undefined, sampleType:'', instrumentName:'', instrumentType:1, instrumentClass:'', companyId:'', id:'', brandType:'', model:'', networkInterface:'', serverPort:'', serverIp:'', serialPortName:'', baudRate:'', checkBit:'', dataBit:'', stopBit:'', databaseType:'', databaseAddress:'', username:'', password:'', coding:'', readFrequency:'', filePath:'', specimenRule:''})
//表单清除控制
const resetFieldsFlag = ref(false)

// 清除表单数据
const validateFlag = ref(false)

//下拉选择数据 标本类型
const sampleKindSelete = ref<Array<SeleteData>>([])

//下拉选择数据 仪器类型
const typeSelete = ref<Array<SeleteData>>([])

const communicationTypeList = ref<Array<SeleteData>>([])
const networkInterfaceList = ref<Array<SeleteData>>([])
const serialPortNameList = ref<Array<SeleteData>>([])
const baudRateList = ref<Array<SeleteData>>([])
const checkBitList = ref<Array<SeleteData>>([])
const dataBitList = ref<Array<SeleteData>>([])
const stopBitList = ref<Array<SeleteData>>([])
const databaseTypeList = ref<Array<SeleteData>>([])
const codingList = ref<Array<SeleteData>>([])
const specimenRuleList = ref<Array<SeleteData>>([])

//下拉选择数据
const domesticImportedSelete = ref<Array<SeleteData>>([])

//下拉选择数据 ppp
const reagentSelete = ref<Array<SeleteData>>([])

//下拉选择数据
const mechanismSelete = ref<Array<SeleteData>>([])

//tab下标
const activeindex = ref<number>(0)


// 弹窗标题
const lineData = ref<Array<string>>(['基本信息', '通讯协议'])
const baseRule = {
  instrumentName: [
    { required: true, message: '请输入汉字、字母、数字、字符', trigger: 'change' },
    // { required: true, message: '请输入汉字、字母、数字、字符', pattern:Normal, trigger: ['change', 'blur']},
    { required: false, message: '首尾不能为空', pattern:NotLeadingAndTrailingSpaces, trigger: ['change', 'blur']},
    {required:true, message:'长度应不超过50个字符', max:50, trigger: ['change', 'blur']}
  ],
  instrumentType: [
    { required: true, message: '请选择', trigger: ['change', 'blur']}
  ],
  specimenRule: [
    { required: true, message: '请选择', trigger: ['change', 'blur']}
  ],
  reagents: [
    { required: true, message: '请选择', trigger: ['change', 'blur']}
  ],
  maxSpecimen:[
    { required: true, message: '请输入最大标本号', trigger: 'change' },
    { required: true, message: '请输入正整数', pattern:PositiveInteger, trigger: ['change', 'blur']},
    { required: true, message:'标本号最大为999999999', max:9, trigger: ['change', 'blur']}
  ],
  model:[
    { required: false, message: '请输入汉字、字母、数字、字符', trigger: 'change' },
    // { required: false, message: '请输入汉字、字母、数字、字符', pattern:Normal, trigger: ['change', 'blur']},
    { required: false, message: '首尾不能为空', pattern:NotLeadingAndTrailingSpaces, trigger: ['change', 'blur']},
    {required:false, message:'长度应不超过50个字符', max:50, trigger: ['change', 'blur']}
  ]
}

const rules = ref<FormRules>()
const ruleI = {
  communicationType: [
    { required: true, message: '请选择', trigger: ['change', 'blur']}
  ],
  networkInterface: [
    { required: true, message: '请选择', trigger: ['change', 'blur']}
  ],
  serverPort: [
    { required: true, message: '请输入端口号', trigger: 'change' },
    { required: true, message: '请输入数字', pattern:Number, trigger: ['change', 'blur']},
    {required:true, message:'长度应不超过20个字符', max:20, trigger: ['change', 'blur']}
  ]
}
const ruleC = {
  communicationType: [
    { required: true, message: '请选择', trigger: ['change', 'blur']}
  ],
  serialPortName: [
    { required: true, message: '请选择', trigger: ['change', 'blur']}
  ],
  baudRate: [
    { required: true, message: '请选择', trigger: ['change', 'blur']}
  ],
  checkBit: [
    { required: true, message: '请选择', trigger: ['change', 'blur']}
  ],
  dataBit: [
    { required: true, message: '请选择', trigger: ['change', 'blur']}
  ],
  stopBit: [
    { required: true, message: '请选择', trigger: ['change', 'blur']}
  ]
}
const ruleS = {
  communicationType: [
    { required: true, message: '请选择', trigger: ['change', 'blur']}
  ],
  databaseType: [
    { required: true, message: '请选择', trigger: ['change', 'blur']}
  ],
  databaseAddress: [
    { required: true, message: '请输入汉字、字母、数字、字符', trigger: 'change' },
    // { required: false, message: '请输入汉字、字母、数字、字符', pattern:Normal, trigger: ['change', 'blur']},
    { required: false, message: '首尾不能为空', pattern:NotLeadingAndTrailingSpaces, trigger: ['change', 'blur']},
    {required:false, message:'长度应不超过100个字符', max:100, trigger: ['change', 'blur']}
  ],
  username: [
    { required: false, message: '请输入汉字、字母、数字、字符', trigger: 'change' },
    // { required: false, message: '请输入汉字、字母、数字、字符', pattern:Normal, trigger: ['change', 'blur']},
    { required: false, message: '首尾不能为空', pattern:NotLeadingAndTrailingSpaces, trigger: ['change', 'blur']},
    {required:false, message:'长度应不超过50个字符', max:50, trigger: ['change', 'blur']}
  ],
  password: [
    { required: false, message: '请输入密码', trigger: 'change' },
    { required: false, message: '请输入字母、数字、符号', pattern:NoChineseEmty, trigger: ['change', 'blur']},
    {required:false, message:'长度应在6~20个字符之间', min:6, max:20, trigger: ['change', 'blur']}

  ],
  readFrequency: [
    { required: false, message: '请输入读取频率', trigger: 'change' },
    { required: false, message: '请输入长度不超过10个字符的数字', pattern:/^[0-9]{1,10}$/, trigger: ['change', 'blur']}
  ],
  filePath: [
    { required: false, message: '请输入汉字、字母、数字、字符', trigger: 'change' },
    // { required: false, message: '请输入汉字、字母、数字、字符', pattern:Normal, trigger: ['change', 'blur']},
    { required: false, message: '首尾不能为空', pattern:NotLeadingAndTrailingSpaces, trigger: ['change', 'blur']},
    {required:false, message:'长度应不超过100个字符', max:100, trigger: ['change', 'blur']}
  ],
  coding:[
    { required: false, message: '请选择编码', trigger: 'change' }
  ]
}
const ruleW = {
  communicationType: [
    { required: true, message: '请选择', trigger: ['change', 'blur']}
  ],
  readFrequency: [
    { required: true, message: '请输入读取频率', trigger: 'change' },
    { required: true, message: '请输入长度不超过10个字符的数字', pattern:/^[0-9]{1,10}$/, trigger: ['change', 'blur']}
  ],
  filePath: [
    { required: true, message: '请输入汉字、字母、数字、字符', trigger: 'change' },
    // { required: true, message: '请输入汉字、字母、数字、字符', pattern:Normal, trigger: ['change', 'blur']},
    { required: false, message: '首尾不能为空', pattern:NotLeadingAndTrailingSpaces, trigger: ['change', 'blur']},
    {required:true, message:'长度应不超过100个字符', max:100, trigger: ['change', 'blur']}
  ]
}


// 保存基本信息
const IfinstrumentSave = () => {
  instrumentSave(fromDatas.value).then(res => {
    if (res.data.code === 200) {
      ElMessage({
        type: 'success',
        message: '操作成功'
      })
      emits('confirm')
    }
  })
}

// 弹窗表单数据
const fromItems5 = ref<Array<FromItem>>([
  {label:'通讯类型', prop:'communicationType', placeholder:'请选择通讯类型',  type:'selete', changeSubmit:false, seleteData:[], disabled:props.disabled},
  {label:'网口类型', prop:'networkInterface',  type:'selete', placeholder:'请选择网口类型', changeSubmit:false, seleteData:networkInterfaceList.value, disabled:props.disabled},
  {label:'端口号', prop:'serverPort', placeholder:'请输入端口号', type:'input', enterSubmit:false, disabled:props.disabled}
])

const allFromItems:Array<Array<FromItem>> = [
  [
    {label:'仪器名称', prop:'instrumentName', placeholder:'请输入仪器名称', type:'input', enterSubmit:false, disabled:props.disabled},
    {label:'仪器分类', prop:'instrumentClass',  type:'selete', changeSubmit:false, seleteData:sampleKindSelete.value, disabled:props.disabled},
    {label:'国产/进口', prop:'brandType',  type:'selete', changeSubmit:false, seleteData:domesticImportedSelete.value, disabled:props.disabled},
    {label:'仪器生产厂家', prop:'companyId',  type:'selete', changeSubmit:false, seleteData:mechanismSelete.value, disabled:props.disabled},
    {label:'仪器型号', prop:'model', placeholder:'请输入仪器型号', type:'input', enterSubmit:false, disabled:props.disabled}
  ],
  //检验仪器
  [
    {label:'仪器名称', prop:'instrumentName', placeholder:'请输入仪器名称', type:'input', enterSubmit:false, disabled:props.disabled},
    {label:'国产/进口', prop:'brandType',  type:'selete', changeSubmit:false, seleteData:domesticImportedSelete.value, disabled:props.disabled},
    {label:'仪器型号', prop:'model', placeholder:'请输入仪器型号', type:'input', enterSubmit:false, disabled:props.disabled},
    {label:'标本类型', prop:'sampleType',  type:'selete', changeSubmit:false, seleteData:sampleKindSelete.value, disabled:props.disabled}
  ],
  [
    {label:'仪器名称', prop:'instrumentName', placeholder:'请输入仪器名称', type:'input', enterSubmit:false, disabled:props.disabled},
    {label:'仪器分类', prop:'instrumentClass',  type:'selete', changeSubmit:false, seleteData:sampleKindSelete.value, disabled:props.disabled},
    {label:'检验仪器类型', prop:'instrumentType',  type:'selete', changeSubmit:false, seleteData:typeSelete.value, disabled:props.disabled},
    {label:'关联试剂', prop:'reagents', multiple:true,  type:'selete', changeSubmit:false, seleteData:reagentSelete.value, disabled:props.disabled},
    {label:'标本号规则', prop:'specimenRule',  type:'selete', changeSubmit:false, seleteData:specimenRuleList.value, disabled:props.disabled},
    {label:'最大标本号', prop:'maxSpecimen', placeholder:'请输入最大标本号', type:'input', enterSubmit:false, disabled:props.disabled},
    {label:'国产/进口', prop:'brandType',  type:'selete', changeSubmit:false, seleteData:domesticImportedSelete.value, disabled:props.disabled},
    {label:'仪器生产厂家', prop:'companyId',  type:'selete', changeSubmit:false, seleteData:mechanismSelete.value, disabled:props.disabled},
    {label:'仪器型号', prop:'model', placeholder:'请输入仪器型号', type:'input', enterSubmit:false, disabled:props.disabled}
  ]]
//1为检验仪器
const isShow = ref(1)

//监听通讯类型下拉框
watch(() => fromDatas.value.communicationType, (newValue) => {
  if (newValue) {
    if (newValue + '' === '1') {
      rules.value = ruleI
      fromItems5.value = [
        {label:'通讯类型', prop:'communicationType', placeholder:'请选择通讯类型',  type:'selete', changeSubmit:false, seleteData:communicationTypeList.value, disabled:props.disabled},
        {label:'网口类型', prop:'networkInterface',  type:'selete', placeholder:'请选择网口类型', changeSubmit:false, seleteData:networkInterfaceList.value, disabled:props.disabled},
        {label:'端口号', prop:'serverPort', placeholder:'请输入端口号', type:'input', enterSubmit:false, disabled:props.disabled}
      ]
    } else if (newValue + '' === '2') {
      rules.value = ruleC
      fromItems5.value = [
        {label:'通讯类型', prop:'communicationType', placeholder:'请选择通讯类型',  type:'selete', changeSubmit:false, seleteData:communicationTypeList.value, disabled:props.disabled},
        {label:'串口名', prop:'serialPortName',  type:'selete', placeholder:'请选择串口名', changeSubmit:false, seleteData:serialPortNameList.value, disabled:props.disabled},
        {label:'波特率', prop:'baudRate',  type:'selete', placeholder:'请选择波特率', changeSubmit:false, seleteData:baudRateList.value, disabled:props.disabled},
        {label:'校验位', prop:'checkBit',  type:'selete', placeholder:'请选择校验位', changeSubmit:false, seleteData:checkBitList.value, disabled:props.disabled},
        {label:'数据位', prop:'dataBit',  type:'selete', placeholder:'请选择数据位', changeSubmit:false, seleteData:dataBitList.value, disabled:props.disabled},
        {label:'停止位', prop:'stopBit',  type:'selete', placeholder:'请选择停止位', changeSubmit:false, seleteData:stopBitList.value, disabled:props.disabled}
      ]
    } else if (newValue + '' === '3') {
      rules.value = ruleS
      fromItems5.value = [
        {label:'通讯类型', prop:'communicationType', placeholder:'请选择通讯类型',  type:'selete', changeSubmit:false, seleteData:communicationTypeList.value, disabled:props.disabled},
        {label:'数据库类型', prop:'databaseType',  type:'selete', placeholder:'请选择数据库类型', changeSubmit:false, seleteData:databaseTypeList.value, disabled:props.disabled},
        {label:'数据库地址', prop:'databaseAddress', placeholder:'请输入数据库地址', type:'input', enterSubmit:false, disabled:props.disabled},
        {label:'用户名', prop:'username', placeholder:'请输入用户名', type:'input', enterSubmit:false, disabled:props.disabled},
        {label:'密码', prop:'password', placeholder:'请输入密码', type:'input', enterSubmit:false, disabled:props.disabled},
        {label:'编码', prop:'coding',  type:'selete', placeholder:'请选择编码', changeSubmit:false, seleteData:codingList.value, disabled:props.disabled},
        {label:'读取频率', prop:'readFrequency', placeholder:'请输入读取频率', type:'slot', slotName:'readFrequency'},
        {label:'文件路径', prop:'filePath', placeholder:'请输入文件路径', type:'input', enterSubmit:false, disabled:props.disabled}
      ]
    } else if (newValue + '' === '4') {
      rules.value = ruleW
      fromItems5.value = [
        {label:'通讯类型', prop:'communicationType', placeholder:'请选择通讯类型',  type:'selete', changeSubmit:false, seleteData:communicationTypeList.value, disabled:props.disabled},
        {label:'读取频率', prop:'readFrequency', placeholder:'请输入读取频率', type:'slot', slotName:'readFrequency'},
        {label:'文件路径', prop:'filePath', placeholder:'请输入文件路径', type:'input', enterSubmit:false, disabled:props.disabled}
      ]
    }
  } else {
    rules.value = ruleI
    fromDatas.value.communicationType  = 1
    fromItems5.value = [
      {label:'通讯类型', prop:'communicationType', placeholder:'请选择通讯类型',  type:'selete', changeSubmit:false, seleteData:communicationTypeList.value, disabled:props.disabled},
      {label:'网口类型', prop:'networkInterface',  type:'selete', placeholder:'请选择网口类型', changeSubmit:false, seleteData:networkInterfaceList.value, disabled:props.disabled},
      {label:'端口号', prop:'serverPort', placeholder:'请输入端口号', type:'input', enterSubmit:false, disabled:props.disabled}
    ]
  }
}, {deep:true, immediate:true})

const onSubmitForm = () => {
  if (activeindex.value < 1 && isShow.value) {
    activeindex.value = activeindex.value + 1
  } else {
    IfinstrumentSave()
  }
}

// 弹窗取消
const onCancel = () => {
  if (!activeindex.value) {
    emits('cancel')
  } else {
    activeindex.value = 0
  }
}
// 弹窗关闭
const onClose = () => {
  emits('close')
  resetFieldsFlag.value = !resetFieldsFlag.value
}
// 弹窗保存
const onConfirm = () => {
  validateFlag.value = !validateFlag.value
}
// 弹窗保存
const onsuer = (index) => {
  activeindex.value = index
}
watch(() => activeindex.value, (newValue) => {
  if (newValue === 1) {
    if (!fromDatas.value.instrumentName) {
      activeindex.value = 0
      validateFlag.value = !validateFlag.value
    }
  }
})

//获取字典数据
const getAllDicData = () => {
  common.getDicData('instrument_communication_type').then((res) => {
    const arr: Array<SeleteData> = transfDicArrData(res)
    arr.forEach((item) => {
      item.value = item.value
      item.label = item.label
      communicationTypeList.value.push(item)
    })
  })
  //国产进口
  common.getDicData('brand_type').then((res) => {
    const arr: Array<SeleteData> = transfDicArrData(res)
    arr.forEach((item) => {
      item.value = item.value
      item.label = item.label
      domesticImportedSelete.value.push(item)
    })
  })
  //标本类型
  common.getDicData('sample_type').then((res) => {
    const arr: Array<SeleteData> = transfDicArrData(res)
    arr.forEach((item) => {
      item.value = item.value
      item.label = item.label
      sampleKindSelete.value.push(item)
    })
  })
  //网口类型
  common.getDicData('network_interface_type').then((res) => {
    const arr: Array<SeleteData> = transfDicArrData(res)
    arr.forEach((item) => {
      item.value = item.value
      item.label = item.label
      networkInterfaceList.value.push(item)
    })
  })
  //串口名
  common.getDicData('serial_port_name').then((res) => {
    const arr: Array<SeleteData> = transfDicArrData(res)
    arr.forEach((item) => {
      item.value = item.value
      item.label = item.label
      serialPortNameList.value.push(item)
    })
  })
  //波特率
  common.getDicData('baud_rate').then((res) => {
    const arr: Array<SeleteData> = transfDicArrData(res)
    arr.forEach((item) => {
      item.value = item.value
      item.label = item.label
      baudRateList.value.push(item)
    })
  })
  //校验位
  common.getDicData('check_bit').then((res) => {
    const arr: Array<SeleteData> = transfDicArrData(res)
    arr.forEach((item) => {
      item.value = item.value
      item.label = item.label
      checkBitList.value.push(item)
    })
  })
  //数据位
  common.getDicData('data_bit').then((res) => {
    const arr: Array<SeleteData> = transfDicArrData(res)
    arr.forEach((item) => {
      item.value = item.value
      item.label = item.label
      dataBitList.value.push(item)
    })
  })
  //停止位
  common.getDicData('stop_bit').then((res) => {
    const arr: Array<SeleteData> = transfDicArrData(res)
    arr.forEach((item) => {
      item.value = item.value
      item.label = item.label
      stopBitList.value.push(item)
    })
  })
  //数据库类型
  common.getDicData('database_type').then((res) => {
    const arr: Array<SeleteData> = transfDicArrData(res)
    arr.forEach((item) => {
      item.value = item.value
      item.label = item.label
      databaseTypeList.value.push(item)
    })
  })
  //字符编码格式
  common.getDicData('encode').then((res) => {
    const arr: Array<SeleteData> = transfDicArrData(res)
    arr.forEach((item) => {
      item.value = item.value
      item.label = item.label
      codingList.value.push(item)
    })
  })

}
// 生命周期

onBeforeMount(() => {
  //重新根据id搜索数据赋给编辑弹窗
  if (formData.value && formData.value.id) {
    if (formData.value.instrumentType === 1) {
      getAllData(formData.value.id).then((res) => {
        if (res) {
          const {data} = res.data
          fromDatas.value = {...fromDatas.value, ...data}
          // fromDatas.value.maxSpecimen = fromDatas.value.maxSpecimen + ''
          if (!fromDatas.value.communicationType)fromDatas.value.communicationType = 1
        }
      }).catch((error) => {
        console.error(error)
      })
    } else {
      getAllData(formData.value.id).then((res) => {
        if (res) {
          const {data} = res.data
          fromDatas.value = {...fromDatas.value, ...data}
          // fromDatas.value.maxSpecimen = fromDatas.value.maxSpecimen + ''
          if (!fromDatas.value.communicationType)fromDatas.value.communicationType = 1
        }
      }).catch((error) => {
        console.error(error)
      })
    }
  } else {
    fromDatas.value.communicationType = 1
  }
  getAllDicData()
})
</script>

<template>
  <d-dialog
    custom-class="wid"
    :title="formData.id?'编辑检验仪器':'新增检验仪器'"
    :show-dialog="showDialog"
    :btntext="activeindex===0?'下一步':'保 存'"
    :hide-save-btn="formData.id&&disabled?true:false"
    :cancel-text="formData.id&&disabled?'关 闭':!isShow?'取 消': activeindex===0?'取 消':'上一步'"
    @cancel="onCancel"
    @confirm="onConfirm"
    @close="onClose"
  >
    <timeLine :line-data="lineData" :active="activeindex" @suer="onsuer" />
    <div :style="{height:'450px'}">
      <d-from
        v-if="activeindex===0&&isShow===0"
        :reset-fields-flag="resetFieldsFlag"
        :validate-flag="validateFlag"
        label-position="right"
        :label-width="120"
        :rules="baseRule"
        :form-data="fromDatas"
        :form-items="allFromItems[0]"
        :form-line-num="1"
        @submit="onSubmitForm"
      />
      <!-- 检验仪器 -->
      <d-from
        v-if="activeindex===0&&isShow===1"
        :reset-fields-flag="resetFieldsFlag"
        :validate-flag="validateFlag"
        label-position="right"
        :label-width="120"
        :rules="baseRule"
        :form-data="fromDatas"
        :form-items="allFromItems[1]"
        :form-line-num="1"
        @submit="onSubmitForm"
      />

      <d-from
        v-if="activeindex===0&&isShow===2"
        :reset-fields-flag="resetFieldsFlag"
        :validate-flag="validateFlag"
        label-position="right"
        :label-width="120"
        :rules="baseRule"
        :form-data="fromDatas"
        :form-items="allFromItems[2]"
        :form-line-num="1"
        @submit="onSubmitForm"
      />
      <d-from
        v-else-if="activeindex===1"
        :reset-fields-flag="resetFieldsFlag"
        :validate-flag="validateFlag"
        label-position="right"
        :label-width="120"
        :rules="rules"
        :form-data="fromDatas"
        :form-items="fromItems5"
        :form-line-num="1"
        @submit="onSubmitForm"
      >
        <template #readFrequency>
          <div :style="{width:'100%',height:'100%',display:'flex',flexDirection:'row'}">
            <el-input v-model="fromDatas.readFrequency" type="text" placeholder="请输入读取频率" />
            <span :style="{marginLeft:'10px'}">s</span>
          </div>
        </template>
      </d-from>
    </div>
    <div style="height: 20px;" />
  </d-dialog>
</template>

<style scoped lang="less">
</style>
<style>
.wid{
  width: 700px;
  height: 750px;
}
</style>